package org.dawfinn.droiditarian;

import org.dawfinn.droiditarian.data.DeedsDBAdapter;
import org.dawfinn.droiditarian.deedsource.InternetDeedSource;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class DeedsUpdaterService extends Service {

	public static final int NOTIFICATION_ID = 7;
	public static final String DEEDS_UPDATED = "org.dawfinn.droiditarian.DEEDS_UPDATED";
	public static final String UPDATE_DEEDS_ACTION = "org.dawfinn.droiditarian.UPDATE_DEEDS";

	public static final String UPDATE_PATH = "http://droiditarian.appspot.com/"
			+ "deeds";

	private DeedsUpdater updater;
	private DeedsDBAdapter db;

	@Override
	public void onCreate() {
		super.onCreate();
		db = new DeedsDBAdapter(this);
		updater = new DeedsUpdater(db, new InternetDeedSource(UPDATE_PATH));
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		Log.i("DeedsUpdaterService", "Started");
		try {
			db.open();
			if (updater.update()) {
				sendNotification();
				sendBroadcast();
			}
		} catch (Exception e) {
			Log.e("DeedsUpdater", "Unexpected exception while updating deeds", e);
		} finally {
			db.close();
		}
	}

	private void sendNotification() {
		String notificationTitle = getString(R.string.notification_title);
		Notification notification = new Notification(R.drawable.notification_icon,
				notificationTitle, System.currentTimeMillis());
		PendingIntent pendingIntent = PendingIntent.getActivity(
				getApplicationContext(), 0, new Intent(this, TabWidget.class), 0);
		notification.setLatestEventInfo(getApplicationContext(),
				notificationTitle, getString(R.string.notification_text), pendingIntent);
		((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
				.notify(NOTIFICATION_ID, notification);
	}

	private void sendBroadcast() {
		Intent broadcastIntent = new Intent(DEEDS_UPDATED);
		sendBroadcast(broadcastIntent);
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

}
